package com.itheima.utils;

import com.itheima.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

import static com.itheima.constant.MessageConstant.*;

public class SmsUtil {
    @Autowired
    private static JedisPool jedisPool;

    private static final Jedis jedis = jedisPool.getResource();

    public static boolean sendSms(String telephone, int code) {
        //短信平台
        RestTemplate restTemplate = new RestTemplate();

        Map<String, String> params = new HashMap<>();
        params.put("sid", "0c71daeb7f24a6ef768cb00b132c5624");
        params.put("token", "38c5b2f652edec2cd5d7d26e58ab510e");
        params.put("appid", "70cabdc8fa3349429417d0580bcead2f");
        params.put("templateid", "564697");
        params.put("param", code + "," + 300);
        params.put("mobile", telephone);
        params.put("uid", "1111");
        ResponseEntity<Map> responseEntity = restTemplate.postForEntity("https://open.ucpaas.com/ol/sms/sendsms", params, Map.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            Map body = responseEntity.getBody();
            String statusCode = body.get("code").toString();
            if ("000000".equals(statusCode)) {
                System.out.println("发短信手机号:" + telephone + ",验证码:" + code);
                return true;
            }
            System.out.println(body.get("msg"));
//            log.info("发短信返回的信息:{}",body.get("msg"));
        }
        return false;
    }

    /**
     * 发验证码
     * 验证码存在redis中, 设置过期时间
     * @param telephone 根据手机号发验证码
     * @param jedisKey 存入jedis的key
     * @return
     */
    public static Result send(String telephone,String jedisKey) {
//        int code = RandomUtils.nextInt(100000, 999999);
        try {
            int code = 123456;
//        boolean flag = sendSms(telephone, code);
            System.out.println("发短信手机号:" + telephone + "   " + "验证码:" + code);
            boolean flag = true;
            if (flag) {
                jedis.setex(jedisKey,300, String.valueOf(code));
                return Result.success(SEND_VALIDATECODE_SUCCESS, null);
            }
            return Result.fail(SEND_VALIDATECODE_FAIL);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
